import {
	addSideEffect,
} from '@babel/helper-module-imports';

export default function({types},{entryFiles,extraEntry,polyfills,extraPolyfills,vConsole}){
	return {
		name:'powerful-cli-inject-polyfills',
		visitor:{
			Program(path,state){
				const filename=state.filename;
				if(entryFiles.has(filename)||extraEntry.some((entry) => {
					if(typeof entry==='string'){
						return filename.includes(entry);
					}else{
						return entry.test(filename);
					}
				})){
					if(vConsole.active){
						addSideEffect(path,'powerful-cli/util/vConsole');
					}
					if(extraPolyfills){
						for(const polyfill of extraPolyfills.slice().reverse()){
							addSideEffect(path, polyfill);
						}
					}
					if(Array.isArray(polyfills)){
						polyfills
							.slice()
							.reverse()
							.forEach((polyfill) => {
								addSideEffect(path,`core-js/${polyfill}`);
							})
					}else if(polyfills){
						addSideEffect(path,'core-js/stable');
					}
				}
			}
		}
	}
};